package win.larryzeal.spring.web.advice;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;

import win.larryzeal.spring.except.UnauthenticatedException;
import win.larryzeal.spring.pojo.User;

/**
 * @ControllerAdvice Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller
 *                   classes.
 *                   默认应用于所有Controller，然而，可以使用其属性来控制应用对象。
 *                   同时，使用@Order来控制多个@ControllerAdvice的顺序。
 * @author LarryZeal
 *
 */
@ControllerAdvice
public class ControllerAdviceTest {

	@ModelAttribute
	public User newUser() {
		System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
		return new User("demo", 17);
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
		// binder.
	}

	@ExceptionHandler(UnauthenticatedException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED) // 设置的优先级最高
	public String processUnauthenticatedException(NativeWebRequest request, UnauthenticatedException e) {
		System.out.println("===========应用到所有@RequestMapping注解的方法，在其抛出UnauthenticatedException异常时执行");
		return "viewName"; // 返回一个逻辑视图名？
	}
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 设置的优先级最高
	public String processException(NativeWebRequest request, Exception e) {
		System.out.println("===========应用到所有@RequestMapping注解的方法，在其抛出Exception异常时执行");
		return "viewName"; // 返回一个逻辑视图名？
	}
}